package service

import (
	"tadmin/models"
	"tadmin/models/dto"
	"tadmin/pkg/orm"
	"time"
)

type SensorService struct {
}

var workerService = &WorkerService{}
var WorkerCache = make(map[string]*dto.WorkerVO)

type QuerySensorReq struct {
	CardNo        string    `json:"cardNo"`
	GlobalSteelNo string    `json:"globalSteelNo"`
	ShiftSteelNo  string    `json:"shiftSteelNo"`
	AnchorBoltNo  string    `json:"anchorBoltNo"`
	Pressure      string    `json:"pressure"`
	WorkUnit      string    `json:"workUnit"`
	WorkPlace     string    `json:"workPlace"`
	Name          string    `json:"name"`
	StartTime     time.Time `json:"startTime"`
	EndTime       time.Time `json:"endTime"`
}

// Query 字典查询
func (s *SensorService) Query(query *QuerySensorReq) ([]models.SensorItem, error) {
	db := orm.DB.Model(&models.SensorItem{})

	//查询条件
	var cardNo, globalSteelNo, shiftSteelNo, anchorBoltNo, pressure = query.CardNo, query.GlobalSteelNo, query.ShiftSteelNo, query.AnchorBoltNo, query.Pressure

	if !query.StartTime.IsZero() {
		db = db.Where("gmt_create >= ?", query.StartTime)
	}
	if !query.EndTime.IsZero() {
		db = db.Where("gmt_create <= ?", query.EndTime)
	}
	if query.WorkUnit != "" {
		db = db.Where("work_unit = ?", query.WorkUnit)
	}
	if query.WorkPlace != "" {
		db = db.Where("work_place = ?", query.WorkPlace)
	}
	if query.Name != "" {
		db = db.Where("name = ?", query.Name)
	}
	if globalSteelNo != "" {
		db = db.Where("global_steel_no = ?", globalSteelNo)
	}
	if cardNo != "" {
		db = db.Where("card_no = ?", cardNo)
	}
	if shiftSteelNo != "" {
		db = db.Where("shift_steel_no = ?", shiftSteelNo)
	}
	if anchorBoltNo != "" {
		db = db.Where("anchor_bolt_no = ?", anchorBoltNo)
	}
	if pressure != "" {
		db = db.Where("pressure = ?", pressure)
	}

	//查询数据
	var list []models.SensorItem
	err := db.Order("gmt_create ASC").Find(&list).Error
	if err != nil {
		return nil, err
	}

	return list, err
}

func (s *SensorService) Add(addDto *dto.SensorAddDto) error {

	cardNo := addDto.CardNo

	worker := WorkerCache[cardNo]
	var err2 error

	if worker == nil {
		worker, err2 = workerService.QueryByCardNo(cardNo)
		WorkerCache[cardNo] = worker
	}

	if err2 != nil {
		return err2
	}

	var sensor = &models.SensorItem{
		Name:          worker.Name,
		WorkUnit:      worker.WorkUnit,
		WorkPlace:     worker.WorkPlace,
		CardNo:        addDto.CardNo,
		GlobalSteelNo: addDto.GlobalSteelNo,
		ShiftSteelNo:  addDto.ShiftSteelNo,
		AnchorBoltNo:  addDto.AnchorBoltNo,
		Pressure:      addDto.Pressure,
		GmtCreate:     time.Now(),
		GmtModify:     time.Now(),
	}

	err := orm.DB.Create(sensor).Error
	return err
}
